﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class ExcelManager
{
    //单例
    private static ExcelManager instance;

    private static string Excel_Resource_Path = "ExcelData/";
    
    Dictionary<Type, object> excelDataDic = new Dictionary<Type, object>();

    static ExcelManager()
    {
        instance = new ExcelManager();
    }
    
    public static ExcelManager Instance()
    {
        return instance;
    }
    
    public T GetExcelData<T, V>() where T : ExcelDataBase<V> where V : ExcelItemBase
    {
        Type type = typeof(T);
        if (excelDataDic.ContainsKey(type) && excelDataDic[type] is T)
            return excelDataDic[type] as T;

        T excelData = Resources.Load<T>(Excel_Resource_Path + type.Name);

        if (excelData != null)
            excelDataDic.Add(type, excelData as T);
 
        return excelData;
    }
 
    public V GetExcelItem<T, V>(int Id) where T : ExcelDataBase<V> where V : ExcelItemBase
    {
        var excelData = GetExcelData<T, V>();
 
        if (excelData != null)
            return excelData.GetExcelItem(Id);
        return null;
    }
	
#if UNITY_EDITOR
	public void AddItem<T, V>(V singleItem) where T : ExcelDataBase<V> where V : ExcelItemBase
	{
		string path = "Assets/Resources/" + Excel_Resource_Path;
		
		var excelData = GetExcelData<T, V>();
		if (excelData != null && singleItem != null)
		{
			V[] items = excelData.GetAllItems();
			Array.Resize(ref items, items.Length + 1);
			items[items.Length - 1] = singleItem;
			excelData.itemDic.Clear();
			//先删除记录的旧文件
			if (excelDataDic != null && excelDataDic.ContainsKey(typeof(T)))
			{
				excelDataDic.Remove(typeof(T));
			}
			//替换excelAssetPath下的同名.asset文件
			T excelDataAsset = ScriptableObject.CreateInstance<T>();
			excelDataAsset.items = items;
			if (!System.IO.Directory.Exists(path))
				System.IO.Directory.CreateDirectory(path);
			string pullPath = path + "/" + typeof(T).Name + ".asset";
			UnityEditor.AssetDatabase.DeleteAsset(pullPath);
			UnityEditor.AssetDatabase.CreateAsset(excelDataAsset, pullPath);
			UnityEditor.AssetDatabase.Refresh();
		}
	}
#endif

    
}
